#include "stdafx.h"

#include "XMLNode.h"

#include "Utilities.h"

using namespace std;

namespace ZeEngine
{
    XMLNode::~XMLNode()
    {
        for(XMLNodeMap::iterator it = m_Children.begin(); it != m_Children.end(); ++it)
        {
            Utilities::SafeDelete<XMLNode>(it->second);
        }
    }

    XMLNode* XMLNode::AddChild(const std::string& iName)
    {
        XMLNode* pNode = new XMLNode();

        if (pNode)
        {
            pNode->m_Name = iName;
            m_Children.insert(XMLNodeMapPair(pNode->m_Name, pNode));
        }

        return pNode;
    }

    void XMLNode::AddAttribute(const std::string& iName, const std::string& iValue)
    {
        m_Attributes.insert(XMLNodeAttributeMapPair(iName, iValue));
    }

    void XMLNode::SetValue(const std::string& iValue)
    {
        m_Value = iValue;
    }

    void XMLNode::SetName(const std::string& iName)
    {
        m_Name = iName;
    }

    void XMLNode::Search(const std::string& iName, XMLNodeList& oList) const
    {
        SearchForNodes(iName, oList, *this);
    }

    void XMLNode::SearchForNodes(const std::string& iPath, XMLNodeList& oList, const XMLNode& iNode) const
    {
        vector<string> tokens;
        Utilities::Tokenize(iPath, '.', tokens);

        if (iPath.find(".") == -1)
        {
            if (iNode.m_Name == iPath)
            {  
                oList.push_back(&iNode);
            }
        }
        else
        {
            if (tokens.size() > 0)
            {
                for(XMLNodeMap::const_iterator map = iNode.m_Children.find(tokens[0]); map != iNode.m_Children.end(); ++map)
                {
                    std::string nextPath = iPath.substr(iPath.find_first_of(".") + 1, iPath.length());
                    SearchForNodes(nextPath, oList, *(map->second));
                }
            }
        }
    }
}

